package com.sbw.wx.controller;

import com.alibaba.fastjson.JSONObject;
import com.sbw.wx.entity.sourcematerial.GraphicMessageArticlesBean;
import com.sbw.wx.entity.sourcematerial.GraphicMessageBean;
import com.sbw.wx.entity.sourcematerial.GraphicMessageResp;
import com.sbw.wx.path.RequestPathConst;
import com.sbw.wx.utils.AccessTokenUtil;
import com.sbw.wx.utils.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.URISyntaxException;
import java.text.MessageFormat;

/**
 * Desc: 素材控制器
 * @Date: 2021/6/27 8:58
 * @Author: Lee
 * 面朝大海  春暖花开
 * */
@Slf4j
@RestController
@RequestMapping("/sourceMaterial")
public class SourceMaterialController {

    @Autowired
    private AccessTokenUtil accessTokenUtil;
    @Autowired
    private RestTemplate restTemplate;

    /**
     * Desc: 上传图文消息素材
     * @Date: 2021/6/27 10:27
     * @Author: Lee
     * 面朝大海  春暖花开
     * */
    @PostMapping("/publishGraphicMessage")
    public GraphicMessageResp publishGraphicMessage(@RequestBody GraphicMessageArticlesBean<GraphicMessageBean> graphicMessageArticlesBean){
        GraphicMessageResp graphicMessageResp = null;
        log.info("上传图文消息到微信服务器开始");
        String publishGraphicMessageUrl = MessageFormat.format(RequestPathConst.publishGraphicMessage, accessTokenUtil.getAccessToken());
        log.info("上传图文消息到微信服务器开始，上传url是:{}", publishGraphicMessageUrl);
        String requestJson = JSONObject.toJSONString(graphicMessageArticlesBean);
        log.info("上传图文消息到微信服务器，请求参数是:{}", requestJson);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> request = new HttpEntity(requestJson, headers);
        ResponseEntity<String> responseEntityStr = restTemplate.postForEntity(publishGraphicMessageUrl, request, String.class);
        JSONObject retObj = JSONObject.parseObject(responseEntityStr.getBody());
        if (StringUtils.isEmpty(retObj.getString("errcode"))) {
            graphicMessageResp = new GraphicMessageResp(retObj.getJSONArray("item"), retObj.getString("type"), retObj.getString("media_id"), retObj.getLong("created_at"));
            log.info("上传图文消息到微信服务器结束，返回结果是:{}", graphicMessageResp.toString());
            return graphicMessageResp;
        }
        log.error("上传图文消息到微信服务器异常，异常Code:{}, 异常信息:{}", retObj.get("errcode"), retObj.getString("errmsg"));
        return graphicMessageResp;
    }

    /**
     * Desc: 获取缩略图的id TODO 该接口有问题
     * @Date: 2021/6/27 17:58
     * @Author: Lee
     * 面朝大海  春暖花开
     * */
    @GetMapping("/uploadThumb2Wx")
    public String uploadThumb2Wx(@RequestParam("filePath") String filePath, @RequestParam("sourceType") String sourceType){
        String uploadUrl = MessageFormat.format(RequestPathConst.uploadThumb2Wx, accessTokenUtil.getAccessToken(), sourceType);
        log.info("上传缩略图到微信服务器，上传的Url是:{}", uploadUrl);
        String retInfo = FileUtil.uploadFile2WxServer(uploadUrl, filePath);
        log.info("上传缩略图到微信服务器结束，返回信息:{}", retInfo);
        JSONObject retObj = JSONObject.parseObject(retInfo);
        String errCode = retObj.getString("errcode");
        if (!StringUtils.isEmpty(errCode)){
            log.error("上传缩略图到微信服务器异常，异常Code:{}, 异常信息:{}", retObj.get("errcode"), retObj.getString("errmsg"));
            return "";
        }
        return retObj.toString();
    }

    /**
     * Desc: 上传素材到微信    TODO 该接口目前知道的不能上传视频
     * @Date: 2021/6/27 14:59
     * @Author: Lee
     * 面朝大海  春暖花开
     * isTempSource: 0:上传临时素材 1:上传永久素材   TODO 发布图文消息是只能使用临时素材返回的media_id
     * sourceType: 媒体文件类型，分别有图片（image）、语音（voice）、视频（video）和缩略图（thumb）
     * @Return media_id & url
     * */
    @GetMapping("/uploadSourceMaterial")
    public String uploadSourceMaterial(@RequestParam("isTempSource") int isTempSource, @RequestParam("filePath") String filePath, @RequestParam("sourceType") String sourceType) throws IOException, URISyntaxException {
        String baseUrl = isTempSource == 0 ? RequestPathConst.uploadTempSourceMaterial : RequestPathConst.uploadSourceMaterial;
        if (isTempSource == 0){
            log.info("上传文件到微信服务器的类型是临时素材");
        } else {
            log.info("上传文件到微信服务器的类型是永久素材");
        }
        String uploadUrl = MessageFormat.format(baseUrl, accessTokenUtil.getAccessToken(), sourceType);
        log.info("上传文件到微信服务器，上传的Url是:{}", uploadUrl);
        String retInfo = FileUtil.uploadFile2WxServer(uploadUrl, filePath);
        log.info("上传文件到微信服务器结束，返回信息:{}", retInfo);
        JSONObject retObj = JSONObject.parseObject(retInfo);
        String errCode = retObj.getString("errcode");
        if (!StringUtils.isEmpty(errCode)){
            log.error("上传文件到微信服务器异常，异常Code:{}, 异常信息:{}", retObj.get("errcode"), retObj.getString("errmsg"));
            return "";
        }
        return retObj.toString();
    }

    /**
     * Desc: 图文消息内容里面的图片要换成微信的链接，微信外部的链接不认
     *       调用前请确保以下两点，本接口不做校验 1.图片大小<1M 2.文件后缀只能是jpg/png
     * @Date: 2021/6/27 9:36
     * @Author: Lee
     * 面朝大海  春暖花开
     *
     * @Return 被转换后的 url
     * */
    @GetMapping("/changePicture2WxUrl")
    public Object changePicture2WxUrl(@RequestParam("filePath") String filePath){
        log.info("上传图片到微信服务器开始，图片地址是:{}", filePath);
        String retFilePath = "";
        // 微信上传图片url
        String uploadUrl = MessageFormat.format(RequestPathConst.changePicture2Wx, accessTokenUtil.getAccessToken());
        log.info("上传图片到微信服务器，上传的Url是:{}", uploadUrl);
        String retInfo = FileUtil.uploadFile2WxServer(uploadUrl, filePath);
        log.info("上传文件到微信服务器结束，返回信息:{}", retInfo);
        JSONObject retPath = JSONObject.parseObject(retInfo);
        String retPathUrl = retPath.getString("url");
        if (!StringUtils.isEmpty(retPathUrl)){
            retFilePath = retPathUrl;
        }
        return retFilePath;
    }

}
